// var Facility = Facility || {};
Build = function(scene, camera) {
    this.scene = scene;
    this.camera = camera;
    this.offsetSize = RoomUtil.OFFSET_SIZE;
    this.projector = new THREE.Projector();
    // 	drawArea:0,don't draw area;1,draw area by blue;2,draw area by red;
    this.drawArea = 0;
    this.areaMesh;
    this.rollOverMesh;
    this.startPoint = new THREE.Vector3;
    this.endPoint = new THREE.Vector3;
    this.cellSize = RoomUtil.CELL_SIZE;
    // this.cellSize=RoomUtil.CELL2D_SIZE;
    this.wallThick = RoomUtil.wallThick;
    this.wallHeight = RoomUtil.wallHeight;
    this.structs = [];

    // 	以绘制完成的room的结构集合。
    this.structures = [];

    // 	绘制room过程中，该room中的地板集合。
    this.roomFloors = [];
    this.planeSize = RoomUtil.PLANE2D_SIZE;
    // this.controls=controls;
    stageSize = {
        width : window.innerWidth,
        height : window.innerHeight
    };
    this.house = new House(this.camera, this.scene, stageSize);
    this.houseStyleId;

    this.structure = null;
    this.structureNum = 1;

    this.operateFlag=-1;
    // roll-over helpers
    
    this.houseMeshList=[];
    this.facilityMeshList=[];

};
Build.prototype.constructor = Build;
Build.prototype.init = function() {

    // this.structure.name = 'group';
    // this.scene.add(this.structure);
    // this.structure3D.name = 'group3D';
    // this.scene.add(this.structure3D);

    //init the roll mesh
    var rollOverGeo = new THREE.PlaneGeometry(this.cellSize, this.cellSize);
    var texture = THREE.ImageUtils.loadTexture(RoomUtil.ROLL_NORMAL_TEXTURE);
    var rollOverMaterial = new THREE.MeshBasicMaterial({
        // color : 0xff0000,
        // opacity : 0.5,
        map : texture,
        transparent : true

    });
    this.rollOverMesh = new THREE.Mesh(rollOverGeo, rollOverMaterial);
    this.rollOverMesh.position = new THREE.Vector3(this.cellSize / 2, this.cellSize / 2, 0);
    this.rollOverMesh.name = "rollOver"
    // this.rollOverMesh.rotation.x = -90 * Math.PI / 180;
    this.scene.add(this.rollOverMesh);

    // grid
    var planeGeo = new THREE.PlaneGeometry(this.planeSize, this.planeSize, this.planeSize / this.cellSize, this.planeSize / this.cellSize);
    // planeGeo.computeBoundingBox();

    this.plane = new THREE.Mesh(planeGeo, new THREE.MeshBasicMaterial({
        color : 0x555555,
        wireframe : true
    }));
    this.plane.name = "plane";
    // this.plane.size = planeGeo.boundingBox.max.subSelf(planeGeo.boundingBox.min);
    // mesh.matrixAutoUpdate = true;
    // this.plane.updateMatrix();
    // this.plane.rotation.x = -90 * Math.PI / 180;
    this.scene.add(this.plane);

    // var theText = "Hello three.js! :)";
    // var text3d = new THREE.TextGeometry( theText, {
    // size: 80,
    // height: 20,
    // curveSegments: 2,
    // font: "helvetiker"
    // });
    // text3d.computeBoundingBox();
    // var centerOffset = -0.5 * ( text3d.boundingBox.max.x - text3d.boundingBox.min.x );
    // var textMaterial = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, overdraw: true } );
    // text = new THREE.Mesh( text3d, textMaterial );
    // this.scene.add(text);

};

Build.prototype.rotateFacility=function(event){
  this.house.facility.rotate(event);
};

Build.prototype.changeFlat=function(){
      this.scene.remove(this.house.roomFloorGroup);
    this.camera.position.y = RoomUtil.y3D;
    // this.camera.position.z = 600;
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));
    this.plane.rotation.x = -90 * (Math.PI / 180 );
 };
    
Build.prototype.loadStructure = function() {
    // // alert('double');
    // this.scene.remove(this.house.roomFloorGroup);
    // this.camera.position.y = 320;
    // // this.camera.position.z = 600;
    // this.camera.lookAt(new THREE.Vector3(0, 0, 0));
    // this.plane.rotation.x = -90 * (Math.PI / 180 );
    // // scene.remove(build.rollOverMesh);

    console.warn(this.structures);

    for(var i in this.structures) {
        var structure3D = new THREE.Object3D;
        structure3D.name = 'structure3D';
        structure3D.roomType = 1;
        structure3D.rndId = RoomUtil.random();
        // this.scene.add(structure3D);

        // var st0 = this.structures[i].structure.children[0];
        // var pz2d = st0.position.z;
        // var sz2d = st0.size.z;
        // st0.position.z = -1 * st0.position.y;
        // st0.position.y = pz2d;
        // st0.size.z = st0.size.y;
        // st0.size.y = sz2d;
        //
        // this.offsetPosition(st0, this.structures[0].structure.children[0], new THREE.Vector3(0, 0, 0));
        // this.showStructure(st0.position, st0.size, structure3D.roomType, structure3D);
        //for(var j = 1; j < this.structures[i].structure.children.length; j++) {
        var st = this.structures[i];
        var pz2d = st.position.z;
        var sz2d = st.size.z;
        // st.position2d={x:x2d,y:y2d,z:z2d};
        st.position.z = -1 * st.position.y;
        st.position.y = pz2d;
        st.size.z = st.size.y;
        st.size.y = sz2d;
        this.offsetPosition(st, this.structures[0], new THREE.Vector3(0, 0, 0));
        this.showStructure(st.position, st.size, structure3D.roomType);
        // structureDetails.push(detail);
    };
    // }

    //structure3D.detail = structureDetails;
    // structure3D.wallsDetails=wallsDetails;
    this.scene.remove(this.house.roomFloorGroup);
    for(var i = 0; i < this.structures.length; i++) {
        //var structure = this.structures[i].structure;
        this.scene.remove(this.structures[i]);
    };
    // this.structures=[];

};

Build.prototype.initStage=function(){
  
  console.warn(this.scene.children.length);
  var tmp=[];
  for(var i=0;i<this.scene.children.length;i++){
    var c=this.scene.children[i];
    console.warn(i);
    // console.warn(c.roomId);
    if(c.roomId){
      // console.warn("removed="+i);
      
      tmp.push(c);
    }
  }
  
    for(var i=0;i<tmp.length;i++){
      this.scene.remove(tmp[i]);
    }
    this.houseStyleId=null;
    this.userHouseId=null;
    this.facilityMeshList=[];
}

Build.prototype.setScene = function(scene) {
    this.scene = scene;
    this.house.setScene(scene);
};
Build.prototype.setCamera = function(camera) {
    this.camera = camera;
    this.house.setCamera(camera);
};
Build.prototype.removeFacility = function() {
    this.facilityMeshList.splice($.inArray(this.house.facility.curMesh, this.facilityMeshList), 1);
    this.house.removeFacility();
};

Build.prototype.initStructureObject3D = function(roomType,roomNum) {

    if(roomType)
        this.strucutreMetadata={roomType:roomType,roomNum:roomNum,rndId:RoomUtil.random()};

};
Build.prototype.saveStyle=function(){
    var house={
      "BuildName":$("#nameval").val(),
      "hTypeId":$("#roomstypeval").val(),
      "area":$("#areaval").val(),
      "address":$("#addrval").val(),
      "desc":$("#descval").val(),
      "supplyid":$("#supplyval").val()
    };
    var rooms=[];
    for(s in this.structures) {
        rooms.push({type:parseInt(this.structures[s].roomType),size_x:this.structures[s].size.x,size_y:this.structures[s].size.y,size_z:this.structures[s].size.z,
            position_x:this.structures[s].position.x,position_y:this.structures[s].position.y,position_z:this.structures[s].position.z});

    };
    this.strucutreMetadata=null;
    $.post(saveStyleUrl,{rooms:JSON.stringify(rooms),house:JSON.stringify(house),hs_id:this.houseStyleId}, function(data) {
        console.warn(data);
    });
  
};
Build.prototype.saveHouse = function() {
//未完成


var relFdRses=[];
for(var i in this.facilityMeshList){
  var f=this.facilityMeshList[i];
	var relFDRS={
		fdId:parseInt(f.id),
		rsId:parseInt(f.roomId),
		fdPositionX:parseInt(f.position.x),
		fdPositionY:parseInt(f.position.y),
		fdPositionZ:parseInt(f.position.z),
		fdRotationX:parseInt(f.rotation.x),
		fdRotationY:parseInt(f.rotation.y),
		fdRotationZ:parseInt(f.rotation.z),
		fdSizeX:parseInt(f.size.x),
		fdSizeY:parseInt(f.size.y),
		fdSizeZ:parseInt(f.size.z),
		parasitizedFace:JSON.stringify(f.parasitizedFace),
		frid:parseInt(f.frid)
	}
	relFdRses.push(relFDRS);
}	
  console.warn(this.houseStyleId);
  console.warn(this.userHouseId);
  console.warn(JSON.stringify(relFdRses));
  
  if(this.userHouseId==null){
    $.post(saveHouseUrl,{"relFdRses":JSON.stringify(relFdRses),"hs_id":this.houseStyleId},function(data){
    console.warn(data);
  });
  }else{
	$.post(saveHouseUrl,{"relFdRses":JSON.stringify(relFdRses),"hs_id":this.houseStyleId,"uh_id":this.userHouseId},function(data){
		console.warn(data);
	});
}
};
Build.prototype.loadStyleList=function(){
//按分页获得HouseStyle
};

Build.prototype.startArea = function(event) {
  var mouse2D = RoomUtil.transMouse22D(event);
    // mouse2D.y = -(event.clientY / window.innerHeight ) * 2 + 1;
    var ray = this.projector.pickingRay(mouse2D.clone(), this.camera);

    this.startPoint.copy(this.rollOverMesh.position);
    this.startPoint.z = this.wallThick * 2;
    this.endPoint.copy(this.rollOverMesh.position);
    this.endPoint.z = this.wallThick * 2;
    this.rollOverMesh.visible = false;
    this.drawArea = 1;

};

Build.prototype.endArea = function(event) {
    this.rollOverMesh.visible = true;
    this.scene.remove(this.areaMesh);
    this.setOperateFlag(0);
    if(this.drawArea != 0) {
        this.drawStructure();
        this.drawArea = 0;
    }

    if(this.roomFloors.length > 0) {
        var structure = new THREE.Object3D;
        for(var i = 0; i < this.roomFloors.length; i++) {
            this.scene.remove(this.roomFloors[i]);
            structure=this.roomFloors[i];
            structure.name = 'group';
            this.scene.add(structure);
            this.structures.push(this.roomFloors[i]);
            this.structure = structure;
            this.structure.roomType = this.strucutreMetadata.roomType;
            this.structure.roomNum=this.strucutreMetadata.roomNum;
            this.structure.rndId = this.strucutreMetadata.rndId;
        };
        this.roomFloors = [];
        
        var me=this;
        $('#roomStylePanel').load(popmenuUrl, {
          'hostInfo' :  JSON.stringify({"name":"roomInfo"})
        }, function(data) {
           me.showRoomInfo();
        });


    }

};

Build.prototype.moveRollOverMesh=function(event){
    var mouse2D =RoomUtil.transMouse22D(event);
    var intersects = null;
    var ray = this.projector.pickingRay(mouse2D.clone(), this.camera);
    var intersects = ray.intersectObjects([this.plane]);
    var intersector = this.getRealIntersector(intersects);
        if(intersector) {
            this.rollOverMesh.position.copy(this.setVoxelPosition(intersector));
        }
};

Build.prototype.moveArea = function(event) {
    var mouse2D =RoomUtil.transMouse22D(event);

    var intersects = null;
    var ray = this.projector.pickingRay(mouse2D.clone(), this.camera);
    var intersects = ray.intersectObjects(this.scene.children);

    if(intersects.length > 0) {
        intersector = this.getRealIntersector(intersects);
        if(intersector) {
            this.rollOverMesh.position.copy(this.setVoxelPosition(intersector));
            // this.rollOverMesh.position.z=4;
            if(this.drawArea != 0) {
                this.endPoint.copy(this.rollOverMesh.position);
                this.endPoint.z = this.wallThick * 2;
                this.createArea();
            }

        }

    }

};
Build.prototype.createArea = function() {
    this.scene.remove(this.areaMesh);
    var x = Math.floor(Math.abs(this.startPoint.x - this.endPoint.x) / this.cellSize) * this.cellSize + this.cellSize;
    var y = Math.floor(Math.abs(this.startPoint.y - this.endPoint.y) / this.cellSize) * this.cellSize + this.cellSize;
    var areaGeo = new THREE.PlaneGeometry(x, y);
    var areaMat = new THREE.MeshBasicMaterial({
        color : "0x0080FF",
        opacity : 0.5,
        transparent : true
    });
    areaGeo.computeBoundingBox();
    this.areaMesh = new THREE.Mesh(areaGeo, areaMat);
    this.areaMesh.name = 'tmparea';
    this.areaMesh.size = areaGeo.boundingBox.max.subSelf(areaGeo.boundingBox.min);
    this.areaMesh.position.x = Math.floor(this.endPoint.x + this.startPoint.x) / 2;
    this.areaMesh.position.y = Math.floor(this.endPoint.y + this.startPoint.y) / 2;
    this.areaMesh.position.z = Math.floor(this.endPoint.z + this.startPoint.z) / 2;
    this.areaMesh.intersect = false;
    // var group = this.scene.getChildByName('group');

    //  判断structures中是否有相交。
    for(var i = 0; i < this.structures.length; i++) {
        // var structure = this.structures[i].structure;
        //
        // for(var j = 0; j < structure.children.length; j++) {
        var c = this.structures[i];

        if(c.gTypeId == 'structure') {
            if(RoomUtil.checkRectIntersectOrUnion(this.areaMesh, c) == 1) {
                this.areaMesh.material = new THREE.MeshBasicMaterial({
                    color : "0x86405A",
                    opacity : 0.5,
                    transparent : true
                });
                this.areaMesh.intersect = true;
                break;
            }

        }
        // }
    };

    //  判断roomFloor中是否有相交。
    for(var i = 0; i < this.roomFloors.length; i++) {
        var f = this.roomFloors[i];
        if(RoomUtil.checkRectIntersectOrUnion(this.areaMesh, f) == 1) {
            this.areaMesh.material = new THREE.MeshBasicMaterial({
                color : "0x86405A",
                opacity : 0.5,
                transparent : true
            });
            this.areaMesh.intersect = true;
            break;
        }
    };

    this.scene.add(this.areaMesh);
    this.structure=this.areaMesh;
    this.structure.roomType = this.strucutreMetadata.roomType;
    this.structure.roomNum=this.strucutreMetadata.roomNum;
    this.structure.rndId = this.strucutreMetadata.rndId;
    this.showRoomInfo();
};

Build.prototype.showRoomInfo= function() {
    $('#typeval').val(RoomUtil.getRoomTypeName(this.structure.roomType));
    $('#centerxval').val(this.structure.position.x);
    $('#centeryval').val(this.structure.position.y); 
    $('#sizexval').val(this.structure.size.x/2);
    $('#sizeyval').val(this.structure.size.y/2);
};
Build.prototype.getStructureByRndId = function(rndId) {
    console.warn(rndId);
    for(var i in this.structures){
      if(this.structures[i].rndId==rndId){
          this.setStructure2CurMesh(this.structures[i]);  
        $('#roomStylePanel').load(popmenuUrl, {
          'hostInfo' : "roomInfo"
        }, function() {
            // me.showPanel(hostInfo);
            // console.warn(hostInfo);
        });
          return;
        }
    }
};
Build.prototype.setStructure2CurMesh= function(mesh) {
  
    this.house.facility.curMesh=mesh;
    // $('#roomStyleList .roomStyle').removeClass('selected');
    // var meshid="#"+mesh.rndId;
    //     $(meshid).addClass('selected');
};
Build.prototype.getArea = function(event) {
    // 	只能改变当前room的size。
    event.preventDefault();

    var mouse2D = new THREE.Vector3(0, 0, 0.5);
    mouse2D.x = ((event.clientX - this.offsetSize.x) / $('canvas').width()) * 2 - 1;
    mouse2D.y = -((event.clientY - this.offsetSize.y) / ($('canvas').height())) * 2 + 1;
    var ray = this.projector.pickingRay(mouse2D.clone(), this.camera);
    for(var i = 0; i < this.roomFloors.length; i++) {
        intersects = ray.intersectObjects(this.roomFloors);
        if(intersects.length > 0) {
            this.roomFloors.splice($.inArray(intersects[0].object, this.roomFloors), 1);
            this.scene.remove(intersects[0].object);

        }
    }
};

Build.prototype.drawStructure = function() {
    var rPoint = new THREE.Vector3;
    rPoint.x = this.areaMesh.position.x;
    rPoint.y = this.areaMesh.position.y-this.wallThick ;
    rPoint.z = this.wallThick / 2;
    if(!this.areaMesh.intersect) {
        this.drawFloor(rPoint, this.areaMesh.size);
    }
};
Build.prototype.drawFloor = function(position, size) {
    // this.structure.add(this.house.createFloor(position, size));
    var tmpFloor = this.house.createFloor(position, size);
    this.roomFloors.push(tmpFloor);
    this.scene.add(tmpFloor);
};
Build.prototype.showStructure = function(position, size, roomType,roomId) {
    
    var roomMesh=this.house.showStructure(position, size, roomType);
    roomMesh.roomId=roomId;
    var roomMeshList={roomId:roomId,list:[]};
    roomMeshList.list.push(roomMesh);
    this.houseMeshList.push(roomMeshList);
    
    this.scene.add(roomMesh);

};
Build.prototype.drawWalls = function() {
    // var rPoint = new THREE.Vector3;
    // for(var i = 0; i < this.scene.children.length; i++) {
    // var floor = this.scene.children[i];
    // if(floor.gTypeId == "floor") {
    // rPoint.x = floor.position.x;
    // rPoint.y = floor.position.y;
    // rPoint.z = this.wallThick / 2;
    // this.house.createWalls(rPoint, floor.size);
    // }
    //
    // }

    this.house.createWalls();

};
Build.prototype.getRealIntersector = function(intersects) {

    for(var i = 0; i < intersects.length; i++) {
        var intersector = intersects[i];

        // if(intersector.object != this.rollOverMesh)
        // return intersector;
        if(intersector.object.name == "plane" || intersector.object.name == "subStructure") {
            return intersector;
        }
        // }else if(intersector.object.gTypeId=="floor"){
        // return null;
        // }
    };
    return null;

};
Build.prototype.setVoxelPosition = function(intersector) {
    var tmpVec = new THREE.Vector3();
    tmpVec.copy(intersector.face.normal);

    var voxelPosition = new THREE.Vector3;
    voxelPosition.add(intersector.point, intersector.object.matrixRotationWorld.multiplyVector3(tmpVec));

    voxelPosition.x = Math.floor(voxelPosition.x / this.cellSize) * this.cellSize + this.cellSize / 2;
    voxelPosition.y = Math.floor(voxelPosition.y / this.cellSize) * this.cellSize + this.cellSize / 2;
    // voxelPosition.y = 0;
    // voxelPosition.z = Math.floor(voxelPosition.z / this.cellSize) * this.cellSize+this.cellSize/2 ;
    return voxelPosition;

};
Build.prototype.facade = function() {
    for(var i in this.structs) {
        this.house.gotoFacade(this.structs[i]);
    }
};
Build.prototype.clearStructure = function() {
    this.scene.remove(this.structure);
    this.structure = new THREE.Object3D;
    this.structure.name = 'group';
    this.scene.add(this.structure);
    // this.scene.remove(this.scene.getChildByName('plane'));
    // this.scene.remove(this.scene.getChildByName('rollOver'));
};
Build.prototype.choiceFacility = function(goodsGeo,goodsPosition) {
    // console.warn(goodsGeo);
    // 				目前贴墙纸，无法实现换texture。只能通过增加mesh来实现？
    if(goodsGeo.gTypeId == "0901") {
        this.house.facility.paintSingle(this.facility.curMesh, goodsGeo.geometryPath, 1)
    } else{
        this.house.loadFacility(goodsGeo,goodsPosition,this.house.facility.curMesh,this.facilityMeshList);
        //this.facilityMeshList.push(this.house.facility.curMesh);
      }
        
};


Build.prototype.turnOffAll= function(lights) {
    for(var i=0;i<lights.length;i++) {
        this.scene.remove(lights[i]);
    }
    return [];
};
Build.prototype.turnOn= function(lights) {
    this.house.turnOn(lights);
};
Build.prototype.moveFacility= function(mouse) {
    var mouse2D=RoomUtil.transMouse22D(mouse);
    this.house.moveFacility(mouse2D);
}
Build.prototype.drawThumb = function(ctx, image) {

};
Build.prototype.changeRoomThumb = function(ctx, image, wall) {
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 4;

    ctx.beginPath();

    for(var i = 0; i < wall.details.length; i++) {
        var w = wall.details[i];
        if(w.gTypeId == 'xwall' || w.gTypeId == 'ywall') {

            var moveX = Math.round((Math.round(w.position.x) - Math.round(w.size.x) / 2) / 5)
            + 60;
            var moveY = Math.round((Math.round(w.position.z) - Math.round(w.size.z) / 2) / 5)
            + 60;
            var lineX = Math.round((Math.round(w.position.x) + Math.round(w.size.x) / 2) / 5)
            + 60;
            var lineY = Math.round((Math.round(w.position.z) + Math.round(w.size.z) / 2) / 5)
            + 60;
            ctx.moveTo(moveX, moveY);
            ctx.lineTo(lineX, lineY);
        }

    };

    var pp = ctx.createPattern(image, 'repeat');
    ctx.fillStyle = pp;
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
};
Build.prototype.convertRoomTo2D = function(canvas, image, meshs) {
    // alert(canvas.width);
    var ctx = canvas.getContext("2d");
    var canvasScale = canvas.width / canvas.height;
    this.structure = new THREE.Vector3;
    for(var i = 0; i < meshs.length; i++) {

        var m = meshs[i];
        this.structure.add(m);
        this.scene.remove(m);
        var destX = 5;
        var destY = 5;
        var destHeight, destWidth;
        if(m.size.y > m.size.x) {
            destHeight = canvas.height;
            destWidth = m.size.x * canvas.height / canvas.width;
        } else {
            destWidth = canvas.width;
            destHeight = m.size.y * canvas.height / canvas.width;
        }
        destWidth -= 10;
        destHeight -= 10;
        destX = (canvas.width - destWidth) / 2;
        destY = (canvas.height - destHeight) / 2;

        ctx.drawImage(image, destX, destY, destWidth, destHeight);
        ctx.strokeStyle = "0x4B4B4B";
        ctx.lineWidth = 2;
        ctx.strokeRect(destX, destY, destWidth, destHeight);
        // var imageObj = new Image();
        // imageObj.onload = function(){
        // ctx.drawImage(imageObj, destX, destY, destWidth, destHeight);
        // };
        // imageObj.src = "darth-vader.jpg";

    };
}
Build.prototype.putTo2D = function(ctx, image, wall) {

    ctx.strokeStyle = '#000';
    ctx.lineWidth = 4;

    ctx.beginPath();

    for(var i = 0; i < wall.details.length; i++) {
        var w = wall.details[i];
        if(w.gTypeId == 'xwall' || w.gTypeId == 'ywall') {
            // if(i==0){
            // ctx.moveTo(w.position.x-w.size.x/2,w.position.z-w.size.z/2);
            // ctx.lineTo(w.position.x+w.size.x/2,w.position.z+w.size.z/2);
            // }
            var moveX = Math.round((Math.round(w.position.x) - Math.round(w.size.x) / 2) / 5)
            + 60;
            var moveY = Math.round((Math.round(w.position.z) - Math.round(w.size.z) / 2) / 5)
            + 60;
            var lineX = Math.round((Math.round(w.position.x) + Math.round(w.size.x) / 2) / 5)
            + 60;
            var lineY = Math.round((Math.round(w.position.z) + Math.round(w.size.z) / 2) / 5)
            + 60;
            ctx.moveTo(moveX, moveY);
            ctx.lineTo(lineX, lineY);
        }

    };
    // ctx.moveTo(10, 10);
    // // give the (x,y) coordinates
    // ctx.lineTo(100, 10);
    // ctx.lineTo(100, 30);
    // ctx.lineTo(150, 30);
    // ctx.lineTo(150, 100);
    // ctx.lineTo(0, 100);
    // ctx.lineTo(0, 30);
    // ctx.lineTo(10, 30);
    // ctx.lineTo(10, 10);
    var pp = ctx.createPattern(image, 'repeat');
    ctx.fillStyle = pp;
    ctx.fill();
    ctx.stroke();
    ctx.closePath();

    this.scene.remove(this.structure);

    // for(var i = 0; i < this.scene.children.length; i++) {
    // if(this.scene.children[i].name == 'group') {
    // for(var j = 0; j < this.scene.children[i].children.length; j++) {
    // var child = this.scene.children[i].children[j];
    // if(child.gTypeId == 'structure') {
    // var position = {
    // x : child.position.x,
    // y : this.wallThick / 2,
    // z : child.position.y
    // };
    // var size = {
    // x : child.size.x,
    // y : child.size.z,
    // z : child.size.y
    // };
    // var floor = {
    // "position" : position,
    // "size" : size,
    // "gTypeId" : 'floor'
    // }
    // wallDetails.push(floor);
    // }
    // }
    // }
    // }
};
Build.prototype.calcWalls3D = function(structure3D) {

    // for(var i in this.structures) {
    var fwallsData = [];
    var bwallsData = [];
    var lwallsData = [];
    var rwallsData = [];
    var wallDetails = [];
    // var structure3D = this.structures[i].structure;
    //for(var j = 0; j < structure3D.children.length; j++) {
    var child = structure3D;
    if(child.gTypeId == 'structure') {
        var position = {
            x : child.position.x,
            y : this.wallThick / 2,
            z : child.position.z
        };
        var size = {
            x : child.size.x,
            y : child.size.y,
            z : child.size.z
        };
        var floor = {
            "position" : position,
            "size" : size,
            "gTypeId" : 'floor'
        }
        wallDetails.push(floor);

        var cposition = {
            x : child.position.x,
            y : this.wallThick / 2 + this.wallHeight,
            z : child.position.z
        };
        var ceiling = {
            "position" : cposition,
            "size" : size,
            "gTypeId" : 'ceiling'
        }
        // wallDetails.push(ceiling);

        var fwallPosition = {x:position.x, y:position.y + this.wallHeight / 2, z:position.z + size.z /
        2-this.wallThick/2
    };
    // var fwallPosition = {
    // x : position.x,
    // y : position.y + this.wallHeight / 2,
    // z : position.z + size.z / 2
    // };
    var fwallSize = {
        "x" : size.x - this.wallThick*2,
        // "x" : size.x - this.wallThick,
        "y" : this.wallHeight,
        "z" : this.wallThick
    };
    var fwall = {
        "position" : fwallPosition,
        "size" : fwallSize,
        "gTypeId" : 'xwall'
    };
    var bwallPosition = {x:position.x, y:position.y + this.wallHeight / 2, z:position.z - size.z /
    2+this.wallThick/2
};
// var bwallPosition = {
// x : position.x,
// y : position.y + this.wallHeight / 2,
// z : position.z - size.z / 2
// };
var bwallSize = {
    "x" : size.x - this.wallThick*2,
    // "x" : size.x - this.wallThick,
    "y" : this.wallHeight,
    "z" : this.wallThick
};
var bwall = {
    "position" : bwallPosition,
    "size" : bwallSize,
    "gTypeId" : 'xwall'
};
var rwallPosition = {x:position.x + size.x / 2-this.wallThick/2, y:position.y+ this.wallHeight / 2, z:position.z
};
// var rwallPosition = {
// x : position.x + size.x / 2,
// y : position.y + this.wallHeight / 2,
// z : position.z
// };
var rwallSize = {
    "x" : this.wallThick,
    "y" : this.wallHeight,
    "z" : size.z - this.wallThick*2
    // "z" : size.z - this.wallThick
};
var rwall = {
    "position" : rwallPosition,
    "size" : rwallSize,
    "gTypeId" : 'ywall'
};

var lwallPosition = {x:position.x - size.x / 2+this.wallThick/2, y:position.y + this.wallHeight / 2, z:position.z};
// var lwallPosition = {
// x : position.x - size.x / 2,
// y : position.y + this.wallHeight / 2,
// z : position.z
// };
var lwallSize = {
    "x" : this.wallThick,
    "y" : this.wallHeight,
    "z" : size.z - this.wallThick*2
    // "z" : size.z - this.wallThick
};
var lwall = {
    "position" : lwallPosition,
    "size" : lwallSize,
    "gTypeId" : 'ywall'
};

fwallsData.push(fwall);
bwallsData.push(bwall);
lwallsData.push(lwall);
rwallsData.push(rwall);

//}
// }
// break;
// }
}

var list = [];
var rectB, rectA;
wallDetails = wallDetails.concat(getWallDetails(fwallsData, bwallsData));
wallDetails = wallDetails.concat(getWallDetails(lwallsData, rwallsData));

var struct = {
    structureNum : this.structureNum,
    //id : structure3D.rndId,
    roomType : structure3D.roomType,
    roomId:structure3D.roomId,
    details : wallDetails,
};
this.structureNum++;
this.structs.push(struct);
// }
return struct;
function getWallDetails(wallsData1, wallsData2) {
    var wallsMergin = [];
    while(wallsData1.length > 0) {

        for(var i = 0; i < wallsData1.length; i++) {
            rectA = wallsData1[i];
            for(var j = 0; j < wallsData2.length; j++) {
                rectB = wallsData2[j];
                list = RoomUtil.checkRoomHasWall(rectA, rectB);
                if(list.length == 1) {
                    wallsMergin.push(list[0]);
                    break;
                }
                if(list.length > 1) {
                    break;
                }

            }
            if(list.length != 0) {
                wallsData2.splice($.inArray(rectB, wallsData2), 1);
                for(var k = 0; k < list.length; k++) {
                    if(list[k].on == 'b')
                        wallsData2.push(list[k]);
                }
                break;
            }

        }
        if(list.length == 0)
            wallsMergin.push(rectA);
        for(var i = 0; i < list.length; i++) {
            if(list[i].on == 'a')
                wallsData1.push(list[i]);
            else if(list[i].on == 'n')
                wallsMergin.push(list[i]);
        }
        wallsData1.splice($.inArray(rectA, wallsData1), 1);

    }
    wallsMergin = wallsMergin.concat(wallsData2);
    //		console.warn(wallsMergin);
    return wallsMergin;
};

};
Build.prototype.calcWalls = function(structure) {
    var fwallsData = [];
    var bwallsData = [];
    var lwallsData = [];
    var rwallsData = [];
    var wallDetails = [];

    // for(var i = 'a's's''a;'0; i < this.scene.children.length; i++) {
    // if(this.scene.children[i].name == 'group') {
    for(var j = 0; j < structure.children.length; j++) {
        var child = structure.children[j];
        var py = -1 * child.position.y;
        if(child.gTypeId == 'structure') {
            var position = {
                x : child.position.x,
                y : this.wallThick / 2,
                z : py
            };
            var size = {
                x : child.size.x,
                y : child.size.z,
                z : child.size.y
            };
            var floor = {
                "position" : position,
                "size" : size,
                "gTypeId" : 'floor'
            }
            wallDetails.push(floor);

            var cposition = {
                x : child.position.x,
                y : this.wallThick / 2 + this.wallHeight,
                z : py
            };
            var ceiling = {
                "position" : cposition,
                "size" : size,
                "gTypeId" : 'ceiling'
            }
            // wallDetails.push(ceiling);

            // var fwallPosition = {x:position.x, y:position.y + this.wallHeight / 2, z:position.z + size.z / 2-this.wallThick/2};
            var fwallPosition = {
                x : position.x,
                y : py + this.wallHeight / 2,
                z : position.z + size.z / 2
            };
            var fwallSize = {
                // "x" : size.x - this.wallThick*2,
                "x" : size.x - this.wallThick,
                "y" : this.wallHeight,
                "z" : this.wallThick
            };
            var fwall = {
                "position" : fwallPosition,
                "size" : fwallSize,
                "gTypeId" : 'xwall'
            };
            // var bwallPosition = {x:position.x, y:position.y + this.wallHeight / 2, z:position.z - size.z / 2+this.wallThick/2};
            var bwallPosition = {
                x : position.x,
                y : py + this.wallHeight / 2,
                z : position.z - size.z / 2
            };
            var bwallSize = {
                // "x" : size.x - this.wallThick*2,
                "x" : size.x - this.wallThick,
                "y" : this.wallHeight,
                "z" : this.wallThick
            };
            var bwall = {
                "position" : bwallPosition,
                "size" : bwallSize,
                "gTypeId" : 'xwall'
            };
            // var rwallPosition = {x:position.x + size.x / 2-this.wallThick/2, y:position.y+ this.wallHeight / 2, z:position.z };
            var rwallPosition = {
                x : position.x + size.x / 2,
                y : py + this.wallHeight / 2,
                z : position.z
            };
            var rwallSize = {
                "x" : this.wallThick,
                "y" : this.wallHeight,
                // "z" : size.z - this.wallThick*2
                "z" : size.z - this.wallThick
            };
            var rwall = {
                "position" : rwallPosition,
                "size" : rwallSize,
                "gTypeId" : 'ywall'
            };

            // var lwallPosition = {x:position.x - size.x / 2+this.wallThick/2, y:position.y + this.wallHeight / 2, z:position.z};
            var lwallPosition = {
                x : position.x - size.x / 2,
                y : py + this.wallHeight / 2,
                z : position.z
            };
            var lwallSize = {
                "x" : this.wallThick,
                "y" : this.wallHeight,
                // "z" : size.z - this.wallThick*2
                "z" : size.z - this.wallThick
            };
            var lwall = {
                "position" : lwallPosition,
                "size" : lwallSize,
                "gTypeId" : 'ywall'
            };

            fwallsData.push(fwall);
            bwallsData.push(bwall);
            lwallsData.push(lwall);
            rwallsData.push(rwall);

        }
        // }
        // break;
        // }
    }
    var list = [];
    var rectB, rectA;
    wallDetails = wallDetails.concat(getWallDetails(fwallsData, bwallsData));
    wallDetails = wallDetails.concat(getWallDetails(lwallsData, rwallsData));

    var struct = {
        structureNum : this.structureNum,
        id : structure.rndId,
        roomType : structure.roomType,
        details : wallDetails,
        structure : this.structure
    };
    this.structureNum++;
    // this.structs.push(struct);
    return struct;
    function getWallDetails(wallsData1, wallsData2) {
        var wallsMergin = [];
        while(wallsData1.length > 0) {

            for(var i = 0; i < wallsData1.length; i++) {
                rectA = wallsData1[i];
                for(var j = 0; j < wallsData2.length; j++) {
                    rectB = wallsData2[j];
                    list = RoomUtil.checkRoomHasWall(rectA, rectB);
                    if(list.length == 1) {
                        wallsMergin.push(list[0]);
                        break;
                    }
                    if(list.length > 1) {
                        break;
                    }

                }
                if(list.length != 0) {
                    wallsData2.splice($.inArray(rectB, wallsData2), 1);
                    for(var k = 0; k < list.length; k++) {
                        if(list[k].on == 'b')
                            wallsData2.push(list[k]);
                    }
                    break;
                }

            }
            if(list.length == 0)
                wallsMergin.push(rectA);
            for(var i = 0; i < list.length; i++) {
                if(list[i].on == 'a')
                    wallsData1.push(list[i]);
                else if(list[i].on == 'n')
                    wallsMergin.push(list[i]);
            }
            wallsData1.splice($.inArray(rectA, wallsData1), 1);

        }
        wallsMergin = wallsMergin.concat(wallsData2);
        return wallsMergin;
    };

};
/**
 * check the Union floors
 * true is union; flase is not
 */
Build.prototype.checkHouseStyle = function() {
    var floorsum = 0;
    for(var i = 0; i < this.scene.children.length; i++) {
        var child = this.scene.children[i];
        if(child.gTypeId == 'floor') {
            floorsum++;
            for(var j = 0; j < this.scene.children.length; j++) {
                var c = this.scene.children[j];
                if(c._id != child._id && c.gTypeId == 'floor') {

                    // 					需要A*算法来解决房间是否相连的问题？
                    if(RoomUtil.checkRectIntersectOrUnion(child, c) == 2) {
                        child.union = true;
                        c.union = true;
                        break;
                    }

                }
            }

        }
    }

    if(floorsum == 1) {
        return true;
    }
    for(var i = 0; i < this.scene.children.length; i++) {
        var child = this.scene.children[i];
        if(child.gTypeId == 'floor') {
            console.warn(child._id + "   " + child.union);
            if(child.union == false) {
                return false;
            }
        }
    }

    return true;
};
Build.prototype.getFacility = function(event) {
    if(this.house) {
        this.house.getFacility(event);
        var me=this;
        $.each(this.houseMeshList,function(i,n){
            if(me.house.facility.curMesh.roomId==n.roomId){
               $('#typeval').val(RoomUtil.getRoomTypeName(n.list[0].roomType));
               $('#centerxval').val(n.list[0].position.x);
               $('#centeryval').val(n.list[0].position.z); 
               $('#sizexval').val(n.list[0].size.x/2);
               $('#sizeyval').val(n.list[0].size.z/2);
            }
        });
    
      // $('#roomStylePanel').load('panelRoom',{});
    }
};
Build.prototype.getStructure = function(event) {
    var mouse2D =RoomUtil.transMouse22D(event);
    projector = new THREE.Projector();
    var ray = projector.pickingRay(mouse2D.clone(), this.camera);

    var intersects = ray.intersectObjects(this.structures);
    var me=this;
    if(intersects.length > 0) {
        this.structure = intersects[0].object;
                
        this.setStructure2CurMesh(this.structure);
        this.showRoomInfo();

        var voxelPosition = new THREE.Vector3;
        voxelPosition.add(intersector.point, intersector.object.matrixRotationWorld.multiplyVector3(tmpVec));
        var detail=this.structure;
        voxelPosition.x = Math.floor(voxelPosition.x / this.cellSize) * this.cellSize;
        voxelPosition.z = Math.floor(voxelPosition.z / this.cellSize) * this.cellSize;
        voxelPosition.y = Math.floor(voxelPosition.y / this.cellSize) * this.cellSize;
        voxelPosition.x=(detail.size.x/this.cellSize)%2==1?voxelPosition.x+this.cellSize/2:voxelPosition.x;
        voxelPosition.y=(detail.size.y/this.cellSize)%2==1?voxelPosition.y+this.cellSize/2:voxelPosition.y;
        this.moveOrResizeStructure(voxelPosition);

    }else{
      this.setOperateFlag(0);
      build.startArea(event);
    }
};
Build.prototype.setOffsetPosition = function(detailI, target) {

};
Build.prototype.offsetPosition = function(detailI, detail0, target) {
    detailI.initPosition = {
        x : detailI.position.x,
        z : detailI.position.z
    };

    // if(detailI.position.x == detail0.position.x &&detailI.position.z == detail0.position.z) {
    // detail0.initPosition={x:detailI.position.x,z:detailI.position.z};
    // }

    // if(detailI.gTypeId != 'floor') {
    // 	console.warn('not floor');
    // }
    detailI.position.x -= detail0.initPosition.x - target.x;
    detailI.position.z -= detail0.initPosition.z - target.z;

    // if(detailI.gTypeId=='floor'){
    if(detail0.size.x / this.cellSize % 2 == 1) {
        detailI.position.x -= this.cellSize / 2;
    }

    if(detail0.size.z / this.cellSize % 2 == 1) {
        detailI.position.z -= this.cellSize / 2;
    }
    // }

};
Build.prototype.buildHouse = function(event) {

};
Build.prototype.removeStructure = function() {
    this.scene.remove(this.house.facility.curMesh);
    this.house.facility.curMesh = null;
};
Build.prototype.showRollOver= function() {
    this.rollOverMesh.visible=true;
};

Build.prototype.hideRollOver= function() {
    this.rollOverMesh.visible=false;
};

Build.prototype.operStrucutre=function(event){
    var mouse2D =RoomUtil.transMouse22D(event);
    
    this.toDoStructure(mouse2D);
    
};

Build.prototype.moveStructure=function(mouse2D){
  var projector = new THREE.Projector();
    ray = projector.pickingRay(mouse2D.clone(), this.camera);
    var intersects = ray.intersectObjects(this.structures);
    
    if(intersects.length > 0) {
        intersector = intersects[0];
        if(intersector) {
    
            var tmpVec = new THREE.Vector3();
            tmpVec.copy(intersector.face.normal);
    
            var voxelPosition = new THREE.Vector3;
            voxelPosition.add(intersector.point, intersector.object.matrixRotationWorld.multiplyVector3(tmpVec));
            var detail=this.house.facility.curMesh;
            voxelPosition.x = Math.floor(voxelPosition.x / this.cellSize) * this.cellSize;
            voxelPosition.z = Math.floor(voxelPosition.z / this.cellSize) * this.cellSize;
            voxelPosition.y = Math.floor(voxelPosition.y / this.cellSize) * this.cellSize;
    
    
            voxelPosition.x=(detail.size.x/this.cellSize)%2==1?voxelPosition.x+this.cellSize/2:voxelPosition.x;
            voxelPosition.y=(detail.size.y/this.cellSize)%2==1?voxelPosition.y+this.cellSize/2:voxelPosition.y;
    
            // if(this.outOfPlane(voxelPosition))return;
            var ctrMax = new THREE.Vector3(Math.round(detail.size.x) / 2 + voxelPosition.x, Math.round(detail.size.y) / 2 + voxelPosition.y, Math.round(detail.size.z) / 2 + voxelPosition.z);
            var ctrMin = new THREE.Vector3(voxelPosition.x - Math.round(detail.size.x) / 2, voxelPosition.y - Math.round(detail.size.y) / 2, voxelPosition.z - Math.round(detail.size.z) / 2);
            for(var j in this.structures) {
                var g = this.structures[j];
                if(g != detail) {
                    var gMax = new THREE.Vector3(g.position.x + g.size.x / 2, g.position.y + g.size.y / 2, g.position.z + g.size.z / 2);
                    var gMin = new THREE.Vector3(g.position.x - g.size.x / 2, g.position.y - g.size.y / 2, g.position.z - g.size.z / 2);
                    if(Math.min(ctrMax.x, gMax.x) > Math.max(ctrMin.x, gMin.x) && Math.min(ctrMax.y, gMax.y) > Math.max(ctrMin.y, gMin.y)) {
                        return true;
                    }
                }
            }
            // this.toDoStructure(voxelPosition);
                    this.house.facility.curMesh.position=voxelPosition;
        this.showRoomInfo(); 
    
        }
    }

};


Build.prototype.toDoStructure=function(mouse2D){    
    switch(this.operateFlag){
      case 1:
      this.moveStructure(mouse2D);
      break;
      case 2:
      this.resizeStructure2LeftOnX(mouse2D);
      break;
      case 3:
      this.resizeStructure2RightOnX(mouse2D);
      break;
      case 0:
      this.moveArea(mouse2D);
      break;
      case -1:
      this.moveRollOverMesh(mouse2D);
      break;
    }
};

Build.prototype.resizeStructure2LeftOnX=function(mouse2D){
  var detail=this.house.facility.curMesh;
  var pointStart=new THREE.Vector3(0,0,1);
  pointStart.x=detail.position.x+detail.size.x/2-this.cellSize/2;
  pointStart.y=detail.position.y-detail.size.y/2+this.cellSize/2;
  // this.rollOverMesh.position.copy(pointStart);
  this.startPoint.copy(pointStart);
  this.endPoint.copy(this.rollOverMesh.position);
  this.replaceStructure();
  this.moveArea(mouse2D);
  // this.rollOverMesh.visible=true;
  // this.structure.visible=false;
};

Build.prototype.resizeStructure2RightOnX=function(mouse2D){
  var detail=this.house.facility.curMesh;
  var pointStart=new THREE.Vector3(0,0,1);
  pointStart.x=detail.position.x-detail.size.x/2+this.cellSize/2;
  pointStart.y=detail.position.y-detail.size.y/2+this.cellSize/2;
  // this.rollOverMesh.position.copy(pointStart);
  this.startPoint.copy(pointStart);
  this.endPoint.copy(this.rollOverMesh.position);
  this.replaceStructure();
  this.moveArea(mouse2D);
  // this.rollOverMesh.visible=true;
  // this.structure.visible=false;
};

Build.prototype.replaceStructure=function(){
  this.drawArea=1;
  this.scene.remove(this.structure);
  var i=$.inArray(this.structure, this.structures);
  if(i!=-1)
  this.structures.splice(i, 1);
  this.structure=null;
}

// 判断是move还是resize structure
Build.prototype.moveOrResizeStructure=function(voxelPosition){
    var detail=this.house.facility.curMesh;
    // resize to left
    if((detail.size.x/this.cellSize%2==1&&voxelPosition.x-this.cellSize/2==detail.position.x-detail.size.x/2)||
      (detail.size.x/this.cellSize%2==0&&voxelPosition.x==detail.position.x-detail.size.x/2)
    ){
      this.setOperateFlag(2);
      // alert('resize X on mOr');
    }
    // resize to right
    else if((detail.size.x/this.cellSize%2==1&&voxelPosition.x+this.cellSize/2==detail.position.x+detail.size.x/2)||
      (detail.size.x/this.cellSize%2==0&&voxelPosition.x+this.cellSize==detail.position.x+detail.size.x/2)
    ){
      this.setOperateFlag(3);
      // alert('resize X on mOr');
    }
    // resize to bottom
    else if((detail.size.y/this.cellSize%2==1&&voxelPosition.y-this.cellSize/2==detail.position.y-detail.size.y/2)||
      (detail.size.y/this.cellSize%2==0&&voxelPosition.y==detail.position.y-detail.size.y/2)
    ){
      this.setOperateFlag(4);
      alert('resize Y on bottom');
    }
    // resize to top
    else if((detail.size.y/this.cellSize%2==1&&voxelPosition.y+this.cellSize/2==detail.position.y+detail.size.y/2)||
      (detail.size.y/this.cellSize%2==0&&voxelPosition.y+this.cellSize==detail.position.y+detail.size.y/2)
    ){
      this.setOperateFlag(5);
      alert('resize Y on top');
    }
    
    else{
      this.setOperateFlag(1);
      // alert('move on mOr');
    }
};

/*
 * param flag:
 * -1,move the rollOverMesh;
 * 0, draw the structure;
 * 1,move the strucutre;
 * 2,resize the strucutre to left on the x;
 * 3,resize the strucutre to right on the x;
 * 4,resize the strucutre to bottom on the y;
 * 5,resize the strucutre to top on the y;
 */
Build.prototype.setOperateFlag=function(flag){
  this.operateFlag=flag;
};
Build.prototype.update=function(){
  if(this.house){
    this.house.facility.update();
  }
};
Build.prototype.releaseCache=function(){
      this.structures=[];
      this.structs=[];
      this.rollOverMesh=null;
      this.structureMetadata=null;
      this.startPoint=null;
      this.endPoint=null;
      this.structure=null;
};

Build.prototype.showHouse=function(houseStyle,facilityRoom){
  
    this.initStage();
    // build.showHouseStyle({house_id:houseStyle.id,
    //                       building_name:houseStyle.BuildingInfos.name,
    //                       building_addr:houseStyle.BuildingInfos.address,
    //                       building_supplier:houseStyle.Supplier.abbreviation,
    //                       building_desc:houseStyle.BuildingInfos.description,
    //                       house_desc:houseStyle.description,
    //                       house_area:houseStyle.area});
                          
    var me=this;
  // this.houseStyleId=parseInt(houseStyle.id);
  // this.userHouseId=parseInt(facilityRoom[0].uh_id);
  $('#nameval').val(houseStyle.houseName);
  $('#addrval').val(houseStyle.address);
  $('#descval').val(houseStyle.description);
  $('#supplyval').val(houseStyle.abbreviation);
  $("#areaval").val(houseStyle.area);
  this.changeFlat();
  
         for(var i in houseStyle.RoomStyles){
              var st={roomId:houseStyle.RoomStyles[i].id,position:{x:parseInt(houseStyle.RoomStyles[i].position_x),y:parseInt(houseStyle.RoomStyles[i].position_y),z:parseInt(houseStyle.RoomStyles[i].position_z)},
              size:{x:parseInt(houseStyle.RoomStyles[i].size_x),y:parseInt(houseStyle.RoomStyles[i].size_y),z:parseInt(houseStyle.RoomStyles[i].size_z)},roomType:parseInt(houseStyle.RoomStyles[i].roomType),gTypeId:'structure'};
              this.showStructure(st.position, st.size, st.roomType,st.roomId);
              var walls=this.calcWalls3D(st);
              this.facade(walls);
         }
        $('.stage canvas').bind('click', function(event) {
            me.getFacility(event);
        });
        
        for(var i in facilityRoom){
            var goodsGeo={"geometryPath":facilityRoom[i].FacilityDetails.geometryPath,
                          "gTypeId":facilityRoom[i].FacilityDetails.gTypeId,
                           "_id":facilityRoom[i].FacilityDetails.id,
                           "frid":facilityRoom[i].id,
                           "goodsName":facilityRoom[i].FacilityDetails.name,
                           "dependId":facilityRoom[i].FacilityDetails.dependId,
                           "roomId":facilityRoom[i].rs_id};
            var position={"x":parseInt(facilityRoom[i].position_x),
                               "y":parseInt(facilityRoom[i].position_y),
                               "z":parseInt(facilityRoom[i].position_z)};
            var rotation={"x":0,"y":0,"z":0};                  
            var goodsPos={"position":position,"rotation":rotation,"parasitizedFace":JSON.parse(facilityRoom[i].parasitizedFace)};       

            this.house.loadFacility(goodsGeo,goodsPos,this.house.facility.curMesh,this.facilityMeshList);
            //this.house.setCurMesh(JSON.parse(facilityRoom[i].parasitizedFace));
        }
        
        
               scene.remove(this.rollOverMesh);
              this.releaseCache();
};

Build.prototype.showHouseStyle=function(houseInfo){
  
this.initStage();
  var me=this;
  this.houseStyleId=parseInt(houseInfo.house_id);
  $('#nameval').val(houseInfo.building_name);
  $('#addrval').val(houseInfo.building_addr);
  $('#descval').val(houseInfo.building_desc);
  $('#supplyval').val(houseInfo.building_supplier);
  $("#areaval").val(houseInfo.house_area);

$.post(showRoomStylesUrl,houseInfo, function(data) {
            var s=jQuery.parseJSON(data);
              //console.warn(s);
              me.changeFlat();
         for(var i in s){
              var st={roomId:s[i].id,position:{x:parseInt(s[i].position_x),y:parseInt(s[i].position_y),z:parseInt(s[i].position_z)},
              size:{x:parseInt(s[i].size_x),y:parseInt(s[i].size_y),z:parseInt(s[i].size_z)},roomType:parseInt(s[i].roomType),gTypeId:'structure'};
              me.showStructure(st.position, st.size, st.roomType,st.roomId);
              var walls=me.calcWalls3D(st);
              me.facade(walls);
         }
        $('.stage canvas').bind('click', function(event) {
            build.getFacility(event);
        });
      scene.remove(build.rollOverMesh);
              build.releaseCache();
              $.fancybox.close();
              
             // me.initStage();
          });
          
}
